import ProfileMgr from "../../libs/ProfileMgr";
import $ from "jquery";

$("#gotop").click(function(){
    $("html").scrollTop(0)
})


class BuyCar{
    constructor(){
        this.init.call(this);
    }
    init(){
        this.data = [];
        this.m_cartsCbs = $.Callbacks();
        this.bindEvent();
        this.m_cartsCbs.fire();
    }
    bindEvent(){
        this.m_cartsCbs.add([$.proxy(this.getStorage,this),
            $.proxy(this.render,this)]);
        //删除购物车物品
        let that = this;
        $(".carr").on("click",".remove_cart", function(){
            that.removelist($(this).data("id"))
        })
        $(".paycar").on("mouseenter",function(){
                that.m_cartsCbs.fire();
        })
    }
    
    render(){

        let html =``,
            totalPrice = 0,
            totalCount = 0;
    
        if(this.data.length  == 0){
            html = `<div class="the-none-ware">购物车中还没有商品,赶紧选购吧！</div>`;
        }else{
            html += `<div class="xxbox car-ware">`;
            this.data.forEach((info,index) =>{
               let unitPrice = parseInt(info.price);
               let total = unitPrice * info.count; 
               totalPrice += total;
               totalCount += info.count;

               html +=`<div class="car-ware clear_float ">
               <div class="ware-l">
                   <img
                       src="${info.img}">
               </div>
               <div class="ware-r">
                   <p class="title">${info.name}</p>
                   <div class="ware-b">
                       <span class="size">白色&nbsp;&nbsp;3XL</span>
                       <span class="money">${total.toFixed(2)}</span>
                   </div>

                   <div class="ware-d">
                       <span class="piece dis">x${info.count}</span>
                       <a class="remove_cart remove dis" 
                           data-id="${info.goods_id}">移除</a>
                   </div>
               </div>
           </div>`
            }) ;
            html += `</div>`;
            // 总计
            html += `<p class="total">商品总计：￥<span>${totalPrice.toFixed(2)}</span></p>`
        }
        html += `<a href="./buycar.html" class="sub-cart">
            <div>查看购物车</div>
        </a>`;
        $(".carr").html(html);
        ProfileMgr.setCartCount(totalCount);
        $(".ling").html(totalCount);

    }
    removelist(goodsId){
        ProfileMgr.removeCartListById(goodsId,true);
        this.m_cartsCbs.fire();
    }
    getStorage(){
        ProfileMgr.repeatLoad(); 
        this.data = ProfileMgr.getCartList();
    }

}

module.exports = BuyCar;